package com.lonely.order.support.synchronizer.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.lonely.common.exception.BusinessException;
import com.lonely.order.domain.dto.api.ClothCostFeeItem;
import com.lonely.order.domain.dto.api.GetBigGoodsBomResDTO;
import com.lonely.order.domain.dto.api.PurchaseInfo;
import com.lonely.order.domain.dto.api.QueryProduceOrderInfoByIdResDTO;
import com.lonely.order.domain.entity.SysOrder;
import com.lonely.order.domain.entity.SysOrderPartMaterial;
import com.lonely.order.service.IOrderPartMaterialService;
import com.lonely.order.support.synchronizer.SynchronizerOrderContext;
import com.lonely.order.threadlocals.OrderSynchronizedThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/31 15:30
 * @description: 同步订单部件物料数据服务
 */
@Service
@Slf4j
public class SynchronizerOrderPartMaterialService {

    @Autowired
    private IOrderPartMaterialService orderPartMaterialService;


    /**
     * 同步订单部件物料数据
     *
     * @param synchronizerOrderContext
     */
    public void synchronizerOrderPartMaterial(SynchronizerOrderContext synchronizerOrderContext, Long orderPartId,String sheinPartCode) {
        try {
            // 判断是否已存在
            int count = this.orderPartMaterialService.count(new LambdaQueryWrapper<SysOrderPartMaterial>()
                    .eq(SysOrderPartMaterial::getProduceOrderId, synchronizerOrderContext.getProduceOrderId())
                    .eq(SysOrderPartMaterial::getPartCode, sheinPartCode)
            );
            if (count > 0) {
                log.debug("同步订单号：{}的部件:{} 的物料信息已存在,退出此次同步", synchronizerOrderContext.getProduceOrderId(), sheinPartCode);
                return;
            }

            // 创建物料信息
            saveOrderPartMaterials(synchronizerOrderContext, orderPartId, sheinPartCode);
        } catch (Exception e) {
            log.error("同步订单号：{}的部件:{} 的物料信息失败", synchronizerOrderContext.getProduceOrderId(), sheinPartCode, e);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 保存订单物料 数据
     *
     * @param synchronizerOrderContext
     * @param orderPartId
     * @param partCode
     */
    private void saveOrderPartMaterials(SynchronizerOrderContext synchronizerOrderContext, Long orderPartId,
                                        String partCode) {


        QueryProduceOrderInfoByIdResDTO orderInfoByIdResDTO = synchronizerOrderContext.getOrderInfoById();
        SysOrder sysOrder = synchronizerOrderContext.getNewOrder();

        GetBigGoodsBomResDTO bigGoodsBom = synchronizerOrderContext.getBigGoodsBom();


        // 从订单的采购信息中提取供应商信息，因为单纯的大货bom接口没有供应商相关信息
        Map<String, PurchaseInfo> skuPurchaseMap = new HashMap<>();
        if (CollUtil.isNotEmpty(orderInfoByIdResDTO.getPurchaseInfo())) {
            skuPurchaseMap.putAll(orderInfoByIdResDTO.getPurchaseInfo().stream().collect(Collectors.toMap(PurchaseInfo::getMaterialSku, Function.identity(), (x, y) -> y)));
        }

        // 从订单的物料费用中提取单价相关信息
        List<ClothCostFeeItem> materialItems = orderInfoByIdResDTO.getClothCostFeeDetail().stream().filter(x -> Objects.equals(x.getCategory(), "物料费"))
                .flatMap(x -> x.getClothCostFeeDetail().stream()).collect(Collectors.toList());
        Map<String, ClothCostFeeItem> skuClothCostFeeItemMap = new HashMap<>();
        if (CollUtil.isNotEmpty(materialItems)) {
            skuClothCostFeeItemMap.putAll(materialItems.stream().collect(Collectors.toMap(x -> {
                String title = x.getTitle();
                return title.split("/")[1];
            }, Function.identity(), (x, y) -> y)));
        }

        // 需要过滤出对应部件的物料信息
        List<GetBigGoodsBomResDTO.BigGoodsBom> bigGoodsBoms = bigGoodsBom.getBigGoodsBom();
        if (StrUtil.isNotBlank(partCode)) {
            bigGoodsBoms = bigGoodsBom.getBigGoodsBom().stream().filter(x -> Objects.equals(StrUtil.nullToEmpty(x.getPartCode()), partCode)).collect(Collectors.toList());
        }

        if (CollUtil.isEmpty(bigGoodsBoms)) {
            return;
        }


        // 构建部件物料数据
        for (GetBigGoodsBomResDTO.BigGoodsBom currentBom : bigGoodsBoms) {
            SysOrderPartMaterial sysOrderPartMaterial = new SysOrderPartMaterial();
            sysOrderPartMaterial.setOrderId(sysOrder.getId());
            sysOrderPartMaterial.setOrderPartId(orderPartId);
            sysOrderPartMaterial.setProduceOrderId(Convert.toStr(sysOrder.getProduceOrderId()));
            sysOrderPartMaterial.setPartCode(partCode);
            sysOrderPartMaterial.setGoodsColor(sysOrder.getColor());
            sysOrderPartMaterial.setItem(currentBom.getMaterialType());
            sysOrderPartMaterial.setPartUsed(currentBom.getPart());
            sysOrderPartMaterial.setSinglePieceUsage(currentBom.getOneSimpleUse());
            // 二次工艺
            if (StrUtil.isNotBlank(currentBom.getProcess())) {
                sysOrderPartMaterial.setSecondProcess(JSON.toJSONString(Lists.newArrayList(currentBom.getProcess())));
            }

            sysOrderPartMaterial.setFlowerModel(null);
            sysOrderPartMaterial.setFlowerPatternPic(null);
            sysOrderPartMaterial.setCuttingMethod(null);
            sysOrderPartMaterial.setLoss(currentBom.getSupplierLoss());
            sysOrderPartMaterial.setMaterialName(currentBom.getMaterialName());
            sysOrderPartMaterial.setUnit(currentBom.getUnit());
            sysOrderPartMaterial.setBorderedDoorWidth(currentBom.getWidth());
            sysOrderPartMaterial.setGramWeight(currentBom.getWeight());
            sysOrderPartMaterial.setIngredients(null);
            sysOrderPartMaterial.setMaterialTypeName(currentBom.getFirstClass());
            sysOrderPartMaterial.setMaterialSku(currentBom.getMaterialSku());
            sysOrderPartMaterial.setMaterialColor(currentBom.getColor());
            sysOrderPartMaterial.setMaterialPic(sysOrder.getPic());
            sysOrderPartMaterial.setActualUnitPrice(null);
            sysOrderPartMaterial.setMrpTaxInclusiveUnitPrice(null);
            sysOrderPartMaterial.setStraightBullet(null);
            sysOrderPartMaterial.setHorizontalBullet(null);

            if (skuPurchaseMap.containsKey(currentBom.getMaterialSku())) {
                PurchaseInfo purchaseInfo = skuPurchaseMap.get(currentBom.getMaterialSku());
                sysOrderPartMaterial.setSupplierId(null);
                sysOrderPartMaterial.setSupplierName(purchaseInfo.getSupplierName());
                sysOrderPartMaterial.setSupplierAddress(purchaseInfo.getSupplierAddr());
                sysOrderPartMaterial.setSupplierPhone(purchaseInfo.getSupplierPhone());
                sysOrderPartMaterial.setSupplierCode(purchaseInfo.getSupplierCode());
                sysOrderPartMaterial.setSupplierColorCode(purchaseInfo.getSupplierColorNum());
                sysOrderPartMaterial.setSupplierUnitPrice(null);
            }


            if (skuClothCostFeeItemMap.containsKey(currentBom.getMaterialSku())) {
                ClothCostFeeItem clothCostFeeItem = skuClothCostFeeItemMap.get(currentBom.getMaterialSku());

                // 单价
                sysOrderPartMaterial.setUnitPrice(Convert.toStr(clothCostFeeItem.getUnitPrice()));
                // 供应商利润率
                sysOrderPartMaterial.setSupplierProfitMargin(Convert.toStr(clothCostFeeItem.getProfitRate()));
            }

            sysOrderPartMaterial.setCreateBy(OrderSynchronizedThreadLocal.getCreateBy());
            sysOrderPartMaterial.setUpdateBy(OrderSynchronizedThreadLocal.getCreateBy());

            // 入库
            this.orderPartMaterialService.save(sysOrderPartMaterial);
        }


    }

}
